#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <pthread.h>
#include "log.hpp"
#include "nocopy.hpp"
#include "Comm.hpp"
#include"threadpool.hpp"
#include"task.hpp"

const static int default_backlog = 5;

class TcpServer;
class Thread_Date{
public:
    Thread_Date(int sock,const std::string &ip,const uint16_t &port,TcpServer *t):
        sockfd(sock),ip(ip),port(port),tsvr(t){}
public:
    int sockfd;
    std::string ip;
    uint16_t port;
    TcpServer *tsvr;
};

class TcpServer : public nocopy
{
public:
    TcpServer(uint16_t port) : _port(port), _isrunning(false)
    {
    }
    void Init()
    {
        // 1. 创建socket, file fd, 本质是文件
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            lg.LogMessage(Fatal, "create socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
            exit(Fatal);
        }
        lg.LogMessage(Debug, "create socket success, sockfd: %d\n", _listensock);

        // 2. 填充本地网络信息并bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        //htonl 主机序列转网络序列
        local.sin_addr.s_addr = htonl(INADDR_ANY);//设置ip为本机ip

        // 2.1 bind
        if (bind(_listensock, CONV(&local), sizeof(local)) != 0)
        {
            lg.LogMessage(Fatal, "bind socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
        lg.LogMessage(Debug, "bind socket success, sockfd: %d\n", _listensock);

        // 3. 设置socket为监听状态，tcp特有的
        if (listen(_listensock, default_backlog) != 0)
        {
            lg.LogMessage(Fatal, "listen socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
            exit(Listen_Err);
        }
        lg.LogMessage(Debug, "listen socket success, sockfd: %d\n", _listensock);
    }
    // Tcp 连接全双工通信的.
    void Service(int sockfd)
    {
        char buffer[1024];
        // 一直进行IO
        while (true)
        {
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "client say# " << buffer << std::endl;

                std::string echo_string = "server echo# ";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0) // read如果返回值是0，表示读到了文件结尾(对端关闭了连接！)
            {
                lg.LogMessage(Info, "client quit...\n");
                break;
            }
            else
            {
                lg.LogMessage(Error, "read socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
                break;
            }
        }
    }
    void Start()
    {
        ThreadPool<Task>::GetInstance()->Start();

        //signal(SIGCHLD,SIG_IGN);
        _isrunning = true;
        while (_isrunning)
        {
            // 4. 获取连接
            struct sockaddr_in peer;//远端ip
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensock, CONV(&peer), &len);
            if (sockfd < 0)
            {
                lg.LogMessage(Warning, "accept socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
                continue;
            }
            lg.LogMessage(Debug, "accept success, get a new link: %d\n", sockfd);

            //
            uint16_t client_port = ntohs(peer.sin_port);
            // inet_ntoa 转四字节ip
            //inet_ntop
            char ip_str[32];//client_ip
            inet_ntop(AF_INET,&(peer.sin_addr),ip_str,sizeof(ip_str));

            lg.LogMessage(Debug, "accept success,sockrt: %d,client_ip : %s,client_port: %d\n", sockfd, ip_str,client_port);
            // 5. 提供服务, 单进程
            // Service(sockfd);
            // close(sockfd);

            //多进程
            // pid_t id = fork();
            // if(id == 0){

            //     close(_listensock);
            //     if(fork() > 0 )exit(0);
            //     Service(sockfd);
            //     close(sockfd);
            //     exit(0);
            // }
            // close(sockfd);
            // pid_t rid = waitpid(id,nullptr,0);
            // (void)rid;

            //多线程
            // Thread_Date *td = new Thread_Date(sockfd,ip_str,client_port,this);
            // pthread_t tid;
            // pthread_create(&tid,nullptr,Routine,td);

            //线程池
            Task t(sockfd, ip_str, client_port);
            ThreadPool<Task>::GetInstance()->Push(t);
        }
    }
    // static void * Routine(void *args){
    //     pthread_detach(pthread_self());
    //     Thread_Date *td = static_cast<Thread_Date *>(args);
    //     td->tsvr->Service(td->sockfd);
    //     delete td;
    //     return nullptr;
    // }
    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensock;
    bool _isrunning;
};